package View;

import Controller.CarController;
import Controller.CarRentalController;
import Controller.CustomerController;
import pojo.RentalRecord;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.List;


public class CarRental_window extends Component {
    private JFrame frame = new JFrame("租赁管理界面");

    //租车管理相关
    private JPanel carrentalPanel = new JPanel();//租车面板
    private JTable carrentalTable = new JTable();

    private JLabel lblCarName =new JLabel("车辆ID:");
    private JTextField rentalSearchTextField = new JTextField(10);
    private JButton rentalSearchButton = new JButton("查询车辆租赁情况");
    private JButton rental_quit = new JButton("取消订单");
    /*private JButton rental_lead = new JButton("导入订单");*/
    private JButton rental_export = new JButton("导出订单");
    private String[][] data ;
    private int quit_rentalid = -1;
    private int userId = -1;
    private int carId = -1;


    // 控制
    private CarRentalController carRentalController = new CarRentalController();
    private CustomerController customerController = new CustomerController();
    private CarController carController = new CarController();

    public CarRental_window() throws Exception {
        frameControl();
        close_openmain();
        getSelectId();
    }

    //窗口关闭，打开main_window
    public void close_openmain(){
        // 设置窗口关闭操作为DO_NOTHING_ON_CLOSE
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        // 添加窗口关闭事件监听器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // 这里可以添加你的关闭逻辑
                frame.setVisible(false);
                new Main_window();
            }
        });

    }

    // 设置容器管理
    public void frameControl() throws Exception {
        // 设置底层容器和布局管理器
        frame.setSize(900, 700);
        frame.setLocation(600, 200);
        frame.setResizable(false);

        // 设置车辆面板
        JScrollPane browseScrollPane = new JScrollPane(carrentalTable);
        carrentalPanel.setLayout(new BorderLayout());
        //搜素面板
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        //把搜索面板放入主面板
        searchPanel.add(rental_export,FlowLayout.LEFT);
        /*searchPanel.add(rental_lead,FlowLayout.LEFT);*/
        searchPanel.add(rental_quit,FlowLayout.LEFT);
        searchPanel.add(lblCarName,FlowLayout.LEFT);
        searchPanel.add(rentalSearchTextField,FlowLayout.CENTER);
        searchPanel.add(rentalSearchButton,FlowLayout.RIGHT);
        carrentalPanel.add(searchPanel, BorderLayout.NORTH);

        //把滑动面板放入主面板
        carrentalPanel.add(browseScrollPane, BorderLayout.CENTER);

        // 设置整体布局
        frame.setLayout(new BorderLayout());
        //把面板放入框架
        frame.add(carrentalPanel, BorderLayout.CENTER);

        // 设置按钮事件处理
        setButtonActions();

        // 设置窗口可见性和关闭操作
        frame.setVisible(true);
//        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 初始时获取车辆信息和个人租车信息
        getcarrentalTableData();
    }

    // 当选择了某一行的时候触发该事件
    public void getSelectId(){
        // 使用selection监听器来监听table的哪个条目被选中
        carrentalTable.getSelectionModel().addListSelectionListener(
                new ListSelectionListener() {
                    @Override
                    public void valueChanged(ListSelectionEvent e) {
                        // 获取哪一行被选中了
                        int row = carrentalTable.getSelectedRow();
                        if(row>=0&& !data[row][6].equals("已取消")){
                            quit_rentalid = Integer.parseInt(data[row][0]);
                            userId = Integer.parseInt(data[row][1]);
                            carId = Integer.parseInt(data[row][2]);
                        }else{
                            quit_rentalid = -1;
                            userId = -1;
                            carId = -1;
                        }
                    }
                });

    }

    // 设置按钮事件处理
    public void setButtonActions() {
        //车辆搜索按钮
        rentalSearchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行查询车辆操作
                String searchText = rentalSearchTextField.getText();
                if (searchText.equals("")) {
                    // 如果搜索框为空，显示所有车辆信息
                    try {
                        getcarrentalTableData();
                    } catch (Exception exception) {
                        exception.printStackTrace();
                    }
                } else {
                    // 否则，执行根据条件查询车辆信息
                    try {
                        findRenetal(searchText);
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
        });

        //租车状态取消按钮
        rental_quit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(quit_rentalid >= 0) {
                    try {
                        //更新订单状态“取消”
                        carRentalController.updatestatus(quit_rentalid);
                        carController.updateCarStatus(carId);
                        customerController.updateCustomerStatus(userId);
                        getcarrentalTableData();
                    } catch (Exception throwables) {
                        throwables.printStackTrace();
                    }
                }else{
                    JOptionPane.showMessageDialog(CarRental_window.this, "订单取消失败！", "失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        //租赁导出按钮
        rental_export.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //导出订单操作
                try {
                    CarRentalController.getAllRentalIO();
                    JOptionPane.showMessageDialog(CarRental_window.this, "导出订单成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        });


    }

    // 获取所有租赁信息
    private void getcarrentalTableData() throws Exception {
        List<RentalRecord> centallist = CarRentalController.getAllRental();
        // 模拟获取车辆信息的数据
        String[] header = {"租车ID", "顾客ID", "车辆ID", "租赁开始时间", "租赁结束时间", "租金", "订单状态", "租车天数"};
        data = new String[centallist.size()][8];

        for (int i = 0; i < centallist.size(); i++) {
            RentalRecord rentalRecord = centallist.get(i);
            data[i][0] = String.valueOf(rentalRecord.getRecord_id());
            data[i][1] = String.valueOf(rentalRecord.getCustomer_id());
            data[i][2] = String.valueOf(rentalRecord.getCar_id());
            data[i][3] = String.valueOf(rentalRecord.getStart_date());
            data[i][4] = String.valueOf(rentalRecord.getEnd_date());
            data[i][5] = String.valueOf(rentalRecord.getRental_fee());
            data[i][6] = rentalRecord.getRental_status();
            data[i][7] = String.valueOf(rentalRecord.getRental_days());
        }
        carrentalTable.setModel(new DefaultTableModel(data, header));
    }

    // 查询部分车辆租赁信息
    private void findRenetal(String searchText) throws SQLException {
        if(!searchText.matches("\\d+")){
            JOptionPane.showMessageDialog(CarRental_window.this, "请输入正确的车辆ID！", "失败", JOptionPane.ERROR_MESSAGE);
            return;
        }
        //根据车辆id查询数据
        List<RentalRecord> rental_byCarid = null;
        try {
            //根据车辆id查询数据
            rental_byCarid = carRentalController.getRental_ByCarid(Integer.parseInt(searchText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 模拟查询车辆信息的数据
        String[] header = {"租车ID", "顾客ID", "车辆ID", "租赁开始时间", "租赁结束时间", "租金", "订单状态", "租车天数"};
        System.out.println("点击了查询车辆");
        String[][] data = new String[rental_byCarid.size()][8];

        for (int i = 0; i < rental_byCarid.size(); i++) {
            RentalRecord rentalRecord = rental_byCarid.get(i);
            data[i][0] = String.valueOf(rentalRecord.getRecord_id());
            data[i][1] = String.valueOf(rentalRecord.getCustomer_id());
            data[i][2] = String.valueOf(rentalRecord.getCar_id());
            data[i][3] = String.valueOf(rentalRecord.getStart_date());
            data[i][4] = String.valueOf(rentalRecord.getEnd_date());
            data[i][5] = String.valueOf(rentalRecord.getRental_fee());
            data[i][6] = rentalRecord.getRental_status();
            data[i][7] = String.valueOf(rentalRecord.getRental_days());
        }
        carrentalTable.setModel(new DefaultTableModel(data, header));
    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                CarRental_window carRental_window = new CarRental_window();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }

}
